<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                <el-form-item label="试卷名称" prop="papername">
                      <el-input
                          v-model="queryParams.papername"
                          placeholder="试卷名称"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
                <el-form-item label="试题名称" prop="questionname">
                      <el-input
                          v-model="queryParams.questionname"
                          placeholder="试题名称"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
            type="success"
            @click="handleOpenDialog()"
        >
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
            type="danger"
            :disabled="removeIds.length === 0"
            @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
      </div>

      <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="pageData"
          highlight-current-row
          border
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
    
             
                    <el-table-column
                        key="papername"
                        label="试卷名称"
                        prop="papername"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="questionname"
                        label="试题名称"
                        prop="questionname"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="score"
                        label="分值"
                        prop="score"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="answer"
                        label="正确答案"
                        prop="answer"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="analysis"
                        label="答案解析"
                        prop="analysis"
                        min-width="150"
                        align="center"
                    />
            
					
					<el-table-column label="试题类型" align="center" prop="type" width="150">
					  <template #default="scope">
					    <el-tag :type="scope.row.type == 1 ? 'success' : 'info'">
					      {{ scope.row.type == 1 ? "单选题" : "" }}
						{{ scope.row.type == 2 ? "判断题" : "" }}
						{{ scope.row.type == 3 ? "填空题": "" }}
					    </el-tag>
					  </template>
					</el-table-column>
					
					
					
					
                    <el-table-column
                        key="sequence"
                        label="排序"
                        prop="sequence"
                        min-width="150"
                        align="center"
                    />
					<el-table-column
					    key="createTime"
					    label="创建时间"
					    prop="createTime"
					    min-width="150"
					    align="center"
					/>
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
       
                type="primary"
                size="small"
                link
                @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
                type="danger"
                size="small"
                link
                @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleQuery()"
      />
    </el-card>

    <!-- 试题列表表单弹窗 -->
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="800px"
        @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
                
				
				
				<el-form-item label="选择试卷" prop="paperid">
				  <el-select
				    v-model="formData.paperid"
				    placeholder="请选择试卷"
				    clearable
				    @change="handlePaperChange"
				  >
				    <el-option
				      v-for="paper in paperList"
				      :key="paper.id"
				      :label="paper.name"
				      :value="paper.id"
				    />
				  </el-select>
				</el-form-item>
				

                <el-form-item label="试题名称" prop="questionname">
                      <el-input
                          v-model="formData.questionname"
                          placeholder="试题名称"
                      />
                </el-form-item>
				
				
				<el-form-item label="试题类型" prop="type">
				  <dict  v-model="formData.type" code="STLX" />
				  <el-link underline="never" type="primary" class="ml-5">
				  </el-link>
				</el-form-item>
				
				
               <template v-if="formData.type === '1'">
               				        <el-form-item
               				          v-for="(option, index) in formData.options"
               				          :key="index"
               				          :label="`选项 ${String.fromCharCode(65 + index)}`"
               						  :prop="'options.' + index + '.content'"
               				          :rules="{ required: true, message: '选项内容不能为空', trigger: 'blur' }"
               				        >
               				          <div class="option-item">
               				            <el-input
               				              v-model="option.content"
               				              placeholder="请输入选项内容"
               				              style="width: 65%;display: inline-block;"
               				            ></el-input>
               				            <el-button
               				              v-if="formData.options.length > 2"
               				              type="danger"
               				              @click="removeOption(index)"
               				              circle
               				              size="small"
               				              style="margin-left: 10px;display: inline-block;"
               				            >
										
										 <template #icon><Delete /></template>
										</el-button>
               				          </div>
               				        </el-form-item>
               				        <el-form-item>
               				          <el-button type="primary" @click="addOption">添加选项</el-button>
               				        </el-form-item>
               				  </template>
               				  <!-- 填空题 -->
               				  <template v-else-if="formData.type === 'blank'">
               					    <el-form-item label="参考答案" prop="answer">
               					            <el-input
               					              v-model="formData.answer"
               					              placeholder="请输入参考答案，多个空用 | 分隔"
               					            ></el-input>
               					    </el-form-item>
               					    <el-form-item label="答案解析">
               					            <el-input
               					              v-model="formData.analysis"
               					              type="textarea"
               					              :rows="3"
               					              placeholder="请输入答案解析"
               					            ></el-input>
               					    </el-form-item>
               				</template>
               				 <!-- 判断题 -->
               				<template v-else-if="formData.type === '3'">
               					    <el-form-item label="正确答案" prop="answer">
               					            <el-radio-group v-model="formData.answer">
               					              <el-radio label="T">正确</el-radio>
               					              <el-radio label="F">错误</el-radio>
               					            </el-radio-group>
               					          </el-form-item>
               					        </template>
                

                <el-form-item label="分值" prop="score">
                      <el-input
                          v-model="formData.score"
                          placeholder="分值"
                      />
                </el-form-item>

                <el-form-item label="正确答案" prop="answer">
                      <el-input
                          v-model="formData.answer"
                          placeholder="正确答案"
                      />
                </el-form-item>

                <el-form-item label="答案解析" prop="analysis">
                      <el-input
                          v-model="formData.analysis"
                          placeholder="答案解析"
                      />
                </el-form-item>

     

                <el-form-item label="试题排序，值越大排越前面" prop="sequence">
                      <el-input
                          v-model="formData.sequence"
                          placeholder="试题排序，值越大排越前面"
                      />
                </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  defineOptions({
    name: "ExamQuestion",
    inheritAttrs: false,
  });

  import ExamQuestionAPI, { ExamQuestionPageVO, ExamQuestionForm, ExamQuestionPageQuery } from "@/api/system/exam-question";


  import ExamPaperAPI from "@/api/system/exam-paper";
import { List } from "vxe-table";

  const queryFormRef = ref();
  const dataFormRef = ref();

  const loading = ref(false);
  const removeIds = ref<number[]>([]);
  
  
  const paperList=ref([]);
  
  
  const total = ref(0);

  const queryParams = reactive<ExamQuestionPageQuery>({
    pageNum: 1,
    pageSize: 10,
  });

  // 试题列表表格数据
  const pageData = ref<ExamQuestionPageVO[]>([]);

  // 弹窗
  const dialog = reactive({
    title: "",
    visible: false,
  });

  // 试题列表表单数据
  const formData = reactive<ExamQuestionForm>({
	   type: 0, // 默认单选题
	   score: 1,
	   options: [],
	   answer: '',
	  sequence: 0,
	  
  });

  // 试题列表表单校验规则
  const rules = reactive({
                      id: [{ required: true, message: "请输入主键", trigger: "blur" }],
                      addtime: [{ required: true, message: "请输入创建时间", trigger: "blur" }],
                      paperid: [{ required: true, message: "请输入所属试卷id（外键）", trigger: "blur" }],
                      papername: [{ required: true, message: "请输入试卷名称", trigger: "blur" }],
                      questionname: [{ required: true, message: "请输入试题名称", trigger: "blur" }],
  });

  /** 查询试题列表 */
  function handleQuery() {
    loading.value = true;
          ExamQuestionAPI.getPage(queryParams)
        .then((data) => {
          pageData.value = data.list;
          total.value = data.total;
        })
        .finally(() => {
          loading.value = false;
        });
  }
  
  
    function handlePaperChange(selectedId : String){
  
  	   const selectedPaper = paperList.value.find(paper => paper.id === selectedId);
  	   if (selectedPaper) {
  	        const paperName = selectedPaper.name;
  	        console.log('选中的试卷名称:', paperName);
  	        formData.papername=paperName;
			formData.paperid=selectedId;
  	    }else{
  			console.log(selectedPaper)
  		}
    }
  
  
  function pagerQuery(){
	  ExamPaperAPI.getPaperList().then((data) => {
	       console.log(data)
		   paperList.value=data;
	  })
  }
  
  
    function addOption() {
        if (formData.options.length >= 10) {
             ElMessage.warning('最多只能添加10个选项')
             return
         }
  	  const label = String.fromCharCode(65 + formData.options.length);
        formData.options.push({label, content: '' })
    }
  

  /** 重置试题列表查询 */
  function handleResetQuery() {
    queryFormRef.value!.resetFields();
    queryParams.pageNum = 1;
    handleQuery();
  }

  /** 行复选框选中记录选中ID集合 */
  function handleSelectionChange(selection: any) {
    removeIds.value = selection.map((item: any) => item.id);
  }

  /** 打开试题列表弹窗 */
  function handleOpenDialog(id?: number) {
    dialog.visible = true;
    if (id) {
      dialog.title = "修改试题列表";
            ExamQuestionAPI.getFormData(id).then((data) => {
        Object.assign(formData, data);
		formData.options=JSON.parse(data.options)
      });
    } else {
      dialog.title = "新增试题列表";
    }
  }
  
    // 删除选项
    function removeOption(index){
      if (formData.options.length <= 2) {
        ElMessage.warning('至少需要2个选项')
        return
      }
      formData.options.splice(index, 1)
      
      // 如果是单选题，且删除的是当前选中的选项，则清空答案
      if (formData.type === '1' && formData.answer === String.fromCharCode(65 + index)) {
           formData.answer = ''
      }
    }

  /** 提交试题列表表单 */
  function handleSubmit() {
    dataFormRef.value.validate((valid: any) => {
      if (valid) {
        loading.value = true;
        const id = formData.id;
		console.log(id)
        if (id) {
                ExamQuestionAPI.update(id, formData)
              .then(() => {
                ElMessage.success("修改成功");
                handleCloseDialog();
                handleResetQuery();
              })
              .finally(() => (loading.value = false));
        } else {
                ExamQuestionAPI.add(formData)
              .then(() => {
                ElMessage.success("新增成功");
                handleCloseDialog();
                handleResetQuery();
              })
              .finally(() => (loading.value = false));
        }
      }
    });
  }

  /** 关闭试题列表弹窗 */
  function handleCloseDialog() {
    dialog.visible = false;
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();
    formData.id = undefined;
  }

  /** 删除试题列表 */
  function handleDelete(id?: number) {
    const ids = [id || removeIds.value].join(",");
    if (!ids) {
      ElMessage.warning("请勾选删除项");
      return;
    }

    ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(
        () => {
          loading.value = true;
                ExamQuestionAPI.deleteByIds(ids)
              .then(() => {
                ElMessage.success("删除成功");
                handleResetQuery();
              })
              .finally(() => (loading.value = false));
        },
        () => {
          ElMessage.info("已取消删除");
        }
    );
  }

  onMounted(() => {
    handleQuery();//查询试题列表
	pagerQuery();
	
	
	
	
	
  });
</script>
